import { User } from '../interface/user'
import { AxiosResponse } from 'axios'
import { ActionContext } from 'vuex'
import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Dictionary } from '@/interface/Basic'
import { Message } from 'element-ui'

interface LoginResponse {
  // token: string
  Code: number
  Message: string
  ReturnData: string
}

const state: User = {
  token: getToken(),
  name: '',
  department: '',
  position: '',
  avatar: '',
  roles: [],
  rolesList: {}
}

const mutations = {
  SET_TOKEN: (state: User, token: string) => {
    state.token = token
  },
  SET_NAME: (state: User, name: string) => {
    state.name = name
  },
  SET_DEPARTMENT: (state: User, department: string) => {
    state.department = department
  },
  SET_POSITION: (state: User, position: string) => {
    state.position = position
  },
  SET_AVATAR: (state: User, avatar: string) => {
    state.avatar = avatar
  },
  SET_ROLES: (state: User, roles: string[]) => {
    state.roles = roles
  },
  SET_ROLESLIST: (state: User, rolesList: Dictionary<string>) => {
    const rolsGroup: Dictionary<Dictionary<string>> = {}
    Object.keys(rolesList).forEach(li => {
      const obj: Dictionary<string> = {}
      obj[li] = rolesList[li]
      const key = li.match(/\w+_/)
      if (key && key.length !== 0) {
        rolsGroup[key[0].replace('_', '')] = { ...rolsGroup[key[0].replace('_', '')], ...obj }
      }
    })
    state.rolesList = rolsGroup
  }
}

const actions = {
  // user login
  login({ commit }: ActionContext<User, any>, userInfo: { username: string }) {
    // const { username, password, verifycode } = userInfo
    const { username } = userInfo
    return new Promise((resolve, reject) => {
      login({ IC: username.trim() })
        .then((response: AxiosResponse<LoginResponse>) => {
          const data = response.data
          const token = data.ReturnData
          commit('SET_TOKEN', token)
          setToken(token)
          resolve(token)
        })
        .catch(error => {
          Message({
            message: '登录失败',
            type: 'warning'
          })
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ state, commit }: ActionContext<User, any>) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((response: AxiosResponse<Dictionary<string>[], any>) => {
          const { data } = response
          if (!data) {
            reject(new Error('验证失败，请重新登录'))
          }
          commit('SET_ROLES', ['admin'])
          commit('SET_ROLESLIST', data[0])
          commit('SET_NAME', data[0]['显示值'])
          commit('SET_DEPARTMENT', data[0].DepartmentName)
          commit('SET_POSITION', data[0].Position)
          // commit(
          //   'SET_AVATAR',
          //   'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
          // )
          resolve(state.rolesList)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit }: ActionContext<User, any>) {
    return new Promise(resolve => {
      // logout()
      //   .then(() => {
      //     commit('SET_TOKEN', '')
      //     commit('SET_ROLES', [])
      //     removeToken()
      //     // reset visited views and cached views
      //     // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      //     dispatch('tagsView/delAllViews', null, { root: true })
      //     resolve('logout')
      //   })
      //   .catch(error => {
      //     reject(error)
      //   })
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve('logout')
    })
  },

  // remove token
  resetToken({ commit }: ActionContext<User, any>) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve('resetToken')
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
